package com.feeling.oafeeling.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.feeling.oafeeling.common.pojo.AjaxResult;
import com.feeling.oafeeling.pojo.*;
import com.feeling.oafeeling.service.*;
import com.feeling.oafeeling.utils.util.ServletUtils;
import com.feeling.oafeeling.utils.util.service.TokenService;
import jdk.nashorn.internal.ir.IfNode;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : LiuLi
 * @create 2023/6/21 9:22
 * @工作台控制层
 */
@RestController
@RequestMapping("/task")
public class WorkTaskController {


  @Autowired
  private ICheckReviewRuleService checkReviewRuleService;

  @Autowired
  private TokenService tokenService;

  @Autowired
  private ICheckStepService checkStepService;

  // 创建RestTemplate的bean方便获取
  private RestTemplate restTemplate = new RestTemplate();

  // 首页返回数据集合
  private  List homePagelist = new ArrayList<>();

  // 我对任务页面返回数据集合
  private List myPageList = new ArrayList();

  // 重置获取用户所有已办或者未办
  private List userHaveTask = new ArrayList();

  private Map map = new LinkedHashMap();

  private List mainList = new ArrayList<>();

  private List myList = new ArrayList<>();

  @Autowired
  private ISysUserService userService;

  @Autowired
  private ICheckApprovalProcessService approvalProcessService;

  @Autowired
  private IFlOrderService flOrderService;

  /**
   * 审核任务
   * @return 返回所有任务
   */
  @PostMapping("/auditTask")
  public AjaxResult getAllTask(@RequestParam("reason") String reason){
    AuditTask auditTask = JSON.parseObject(reason, AuditTask.class);
    AuditPost auditPost = new AuditPost();
    HttpServletRequest request = ServletUtils.getRequest();
    Long token = tokenService.verifyToken(request.getHeader("Access-token"));
    SysUser user = userService.findById(token);
    Integer type = flOrderService.findStepId(auditTask.getTaskId(), auditTask.getOrderStatus());
    int doneStus = 0;
    if ("START".equals(auditTask.getOrderStatus())){
      doneStus = 0;
    }else {
      doneStus = Integer.valueOf(auditTask.getOrderStatus());
    }
    int status = doneStus + 1;
    if (type == 0){
      auditPost.setApprovalType("个人");
    }else if (type != 0){
      auditPost.setApprovalType("机构");
    }
    if ("pass".equals(auditTask.getOrderType())){
      if (type == null){
        auditPost.setOrderStatus("OVER");
      }else {
        auditPost.setOrderStatus(String.valueOf(status));
      }
    }else if (!"pass".equals(auditTask.getOrderType())){
      auditPost.setOrderStatus("OVER");
    }

    auditPost.setApprovalBy(user.getUserName());
    auditPost.setStatusReason(auditTask.getStatusReason());
    auditPost.setUpdateBy(user.getUserName());
    HashMap<String,String> map = new HashMap<>();
    map.put("orderNumber", auditTask.getOrderNumber());
    restTemplate.put("http://localhost:8090/api/v1/order/{orderNumber}", auditPost,map);
    return AjaxResult.success();
  }

  /**
   * 获取所有任务 统计数量
   * @return TaskList 返回任务列表及统计
   */
  @GetMapping("/allTask")
  public AjaxResult getOuttanding(){
    List<FlOrder> flOrderList = new ArrayList<>();
    TaskList taskList = new TaskList(new HashSet<>(),new HashSet<>(), new HashSet<>(),new HashSet<>(),new HashSet<>(), 0,0,0);
    // 用来装载任务列表
    homePagelist = restTemplate.getForObject("http://localhost:8090/api/v1/order?orderStatus="+""+"&order?orderType="+"", homePagelist.getClass());
    for (Object o : homePagelist) {
      FlOrder order = new FlOrder();
      FlOrder flOrder = JSON.parseObject(JSON.toJSONString(o), FlOrder.class);
      flOrderList.add(flOrder);
    }
    System.out.println(flOrderList.toString());
    for (FlOrder flOrder : flOrderList) {
      // 将所有任务添加到所有任务列表中
      taskList.getAllTask().add(flOrder);
      // 统计所有任务数
      taskList.setAllTaskNum(taskList.getAllTaskNum() + 1);
      if ("OVER".equals(flOrder.getOrderStatus())){
        // 将已办任务添加在已办列表中
       taskList.getDoneTask().add(flOrder);
       // 统计已办任务数
       taskList.setDoneTaskNum(taskList.getDoneTaskNum() + 1);
      }else if(!"OVER".equals(flOrder.getOrderStatus())){
        // 将未办任务添加到未办列表中
        taskList.getNoDoneTask().add(flOrder);
        // 统计未办任务数
        taskList.setOnDoneTaskNum(taskList.getOnDoneTaskNum() + 1);
      }
    }
    return AjaxResult.success(taskList);
  }

  /**
   * 保存工单
   * @param flOrder 接收请求的数据
   * @return
   */
  @PostMapping("/postTask")
  public AjaxResult postTask(@RequestBody FlOrder flOrder){
    HashMap<String,Object> map = new HashMap<>();
    map.put("orderName", flOrder.getOrderName());
      map.put("orderType", flOrder.getOrderType());
      map.put("orderStatus", flOrder.getOrderStatus());
      map.put("orderDescription", flOrder.getOrderDescription());
      map.put("createBy", flOrder.getCreateBy());
      map.put("updateBy", flOrder.getUpdateBy());
      JSONObject object = new JSONObject(map);
      restTemplate.postForEntity("http://localhost:8090/api/v1/order", object, HashMap.class);
    return AjaxResult.success();
  }

  /**
   * 获取当前登录用户的任务列表
   * @return
   */
  @GetMapping("/getTaskList")
  //@RequestParam(value = "orderType") String orderType
  //@RequestBody OrderType orderType
  public AjaxResult getTaskList(String orderType){
    TaskList taskList = new TaskList(new HashSet<>(),new HashSet<>(), new HashSet<>(),new HashSet<>(),new HashSet<>(), 0,0,0);
//    List<FlOrder> doneList = new ArrayList<>();
//    List<FlOrder> noDoneList = new ArrayList<>();
    List<FlOrder> orders = new ArrayList<>();
    // 获取token中的用户id来查询用户信息
    HttpServletRequest request = ServletUtils.getRequest();
    Long token = tokenService.verifyToken(request.getHeader("Access-token"));
    SysUser user = userService.findById(token);
    HashMap<String,String> idMap = new HashMap<>();
    // 查询任务列表
    System.out.println(orderType);

    if (orderType == null || "null".equals(orderType)){
      System.out.println("`````````````````````````````````");
      myPageList = restTemplate.getForObject("http://localhost:8090/api/v1/order", myPageList.getClass());
    }else {
      myPageList = restTemplate.getForObject("http://localhost:8090/api/v1/order?orderType="+orderType, myPageList.getClass());
    }
    // 遍历列表获取到任务进行的下一个审核人
    FlOrder flOrder = new FlOrder();
    List<FlOrder> done = new ArrayList<>();
//    flOrder = getFlOrder(flOrder,myPageList);
    for (Object o : myPageList) {
      flOrder = JSON.parseObject(JSON.toJSONString(o), FlOrder.class);
      taskList.getAllTask().add(flOrder);
      List<ApprovalRecord> recordList = flOrder.getApprovalRecordList();
      if (!"OVER".equals(flOrder.getOrderStatus()) || "START".equals(flOrder.getOrderStatus())){
        done.add(flOrder);
      }
      // 查询已办任务
        if (flOrder.getApprovalBy().equals(user.getUserName())){
          taskList.getUserDoneTask().add(flOrder);
        }
    }
    // 查询未办任务
    System.out.println(user.getUserId());
    for (FlOrder order : done) {
      List<Integer> ifHave = approvalProcessService.getIfUserTask(orderType, order.getOrderStatus(), user.getUserId());
      if (ifHave.size() != 0){
        taskList.getUserNoDoneTask().add(order);
      }
    }
    System.out.println(done);
    System.out.println(taskList.getUserNoDoneTask().toString());
    return AjaxResult.success(taskList);
  }

  /**
   * 获取用户所有的已办或者未办
   * @param type 用户判断需要的类型 已办或未办
   * @return 返回集合
   */
  @PostMapping("/haveTask")
  public AjaxResult getHaveTask(@RequestParam(value = "type") String type){
    System.out.println("++++++++++++++++++++++"+type);
    Set<FlOrder> haveTask = new HashSet<>();
    userHaveTask = restTemplate.getForObject("http://localhost:8090/api/v1/order", userHaveTask.getClass());
    FlOrder flOrder = new FlOrder();
    HttpServletRequest request = ServletUtils.getRequest();
    Long token = tokenService.verifyToken(request.getHeader("Access-token"));
    SysUser user = userService.findById(token);
    for (Object o : userHaveTask) {
      flOrder = JSON.parseObject(JSON.toJSONString(o), FlOrder.class);
      // 未办任务
      if ("NO".equals(type)){
        if ("START".equals(flOrder.getOrderStatus()) || !"OVER".equals(flOrder.getOrderStatus())){
          System.out.println("未办");
          List<Integer> ifHave = approvalProcessService.getIfUserTask(flOrder.getOrderType(), flOrder.getOrderStatus(), user.getUserId());
          if (ifHave.size() != 0){
            haveTask.add(flOrder);
          }
        }
        // 已办任务
      }else if ("YES".equals(type)){
        System.out.println("已办");
        if ("OVER".equals(flOrder.getOrderStatus()) || !"START".equals(flOrder.getOrderStatus())){
          for (ApprovalRecord approvalRecord : flOrder.getApprovalRecordList()) {
            if (approvalRecord.getTriggerBy().equals(user.getUserName()) && approvalRecord.getOrderId().equals(flOrder.getId())){
              haveTask.add(flOrder);
            }
          }
        }
      }
    }
    return AjaxResult.success(haveTask);
  }
}